package config

import (
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"gopkg.in/yaml.v3"
	"os"
)

// Config 定义全局变量
var Config YamlConfig
var Searcher *xdb.Searcher
var AdminPhone = "13435730481"
var RightIp = "8.134.73.194"

const YmlPath = "./config/config-pro.yaml"
const dbPath = "./config/ip2region.xdb"

type YamlConfig struct {
	ServerConfig *ServerConfig     `yaml:"server"`
	Database     DatabaseConfig    `yaml:"database"`
	DomainIPMap  map[string]string `yaml:"domain_ip_map"`
}

type ServerConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	AppMode  string `yaml:"appMode"`
	Email    string `yaml:"email"`
	Icp      string `yaml:"icp"`
	TempPath string `yaml:"tempPath"`
}

type DatabaseConfig struct {
	Mysql MysqlConfig `yaml:"mysql"`
}

type MysqlConfig struct {
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	LogMode  bool   `yaml:"log-mode"`
}

func init() {
	file, err := os.ReadFile(YmlPath)
	if err != nil {
		fmt.Println("读取配置 config-dev.yaml 失败", err)
	}
	err = yaml.Unmarshal(file, &Config)
	if err != nil {
		fmt.Println("yaml 解析失败")
	}

	// 读取 xdb 数据
	// 1、从 dbPath 加载整个 xdb 到内存
	cBuff, err := os.ReadFile(dbPath)
	if err != nil {
		fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
		fmt.Println("dbPath 解析失败")
	}

	// 2、用全局的 cBuff 创建完全基于内存的查询对象。
	searcher, err := xdb.NewWithBuffer(cBuff)
	if err != nil {
		fmt.Printf("无法创建包含内容的搜索器: %s\n", err)
	}
	// 成功赋值
	Searcher = searcher
}

// InitConfigDev 初始化yaml config
func InitConfigDev() error {
	file, err := os.ReadFile(YmlPath)
	if err != nil {
		fmt.Println("读取配置 config-dev.yaml 失败", err)
		return err
	}

	err = yaml.Unmarshal(file, &Config)
	if err != nil {
		fmt.Println("yaml unmarshal fail")
		return err
	}
	return nil
}

func GetAdminPhone() string {
	return AdminPhone
}

func GetRightIP() string {
	return RightIp
}
